from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import ContentType, Permission, Group
from django.views.generic import View
from .models import Article, User
from .forms import SigninForm


# TODO: 首页视图
class IndexView(View):
    def get(self, request, *args, **kwargs):
        telphone = '18688887788'
        username = 'zhiliao'
        password = 'zhiliao'
        # TODO: 创建普通用户
        # User.objects.create_user(telphone=telphone, username=username, password=password)
        # return HttpResponse('首页')
        return render(request, 'index.html')

# TODO 添加权限
# TODO 通过代码添加权限
class AddPermissionView(View):
    def get(self, request, *args, **kwargs):
        content_type = ContentType.objects.get_for_model(Article)
        permissions = Permission.objects.create(name='拉黑文章', codename='black_article', content_type=content_type)
        return HttpResponse('权限添加成功')


# TODO 操作权限
# TODO 用户与权限管理
class OperatePermissionView(View):
    def get(self, request, *args, **kwargs):
        # TODO 获取用户
        user = User.objects.first()
        # TODO 获取Artcile模型定义权限content_type
        content_type = ContentType.objects.get_for_model(Article)
        # TODO 获取contenttype对应所有权限
        permissions = Permission.objects.filter(content_type=content_type)
        for permission in permissions:
            print(permission, permission.id)
        # 1.直接给定一个权限的列表
        # user.user_permissions.set(permissions)

        # 2.清除权限
        # user.user_permissions.clear()

        # 3.一个个添加权限
        # TODO: *permissions 等价于 permissions[0], permissions[1], permissions[2]...
        # user.user_permissions.add(permissions[0], permissions[1])
        # user.user_permissions.add(*permissions)

        # 4.一个个移除权限
        # TODO: *permissions 等价于 permissions[0], permissions[1], permissions[2]...
        # user.user_permissions.remove(permissions[0], permissions[1])
        # user.user_permissions.remove(*permissions)

        # 5.判断是否拥有
        # 权限参数是一个字符串，格式是app_name.codename。
        # print(user.has_perm('front.view_article'))

        # 6.获取所有的权限
        print(user.get_all_permissions())
        return HttpResponse('权限操作成功')


# TODO 登录视图
class SigninView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'signin.html')

    def post(self, request, *args, **kwargs):
        form = SigninForm(request.POST)
        if form.is_valid():
            telphone = form.cleaned_data.get('telphone')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = authenticate(telphone=telphone, password=password)
            if user:
                login(request, user)
                # TODO: 记住我
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                next_url = request.GET.get('next')
                # TODO: 重定向
                if next_url:
                    return redirect(next_url)
                return redirect(reverse('index'))
            else:
                print('用户名或密码错误')
                return redirect(reverse('signin'))
        else:
            # TODO 登录失败重定向到当前页面
            print(form.errors.get_json_data())
            return redirect(reverse('signin'))


# TODO 退出登录
class LogoutView(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        return redirect(reverse('index'))


# TODO 新增文章视图
class AddArticleView(View):
    # @login_required(login_url='/signin/')
    def get(self, request, *args, **kwargs):
        # TODO: 判断这个用户是否登录
        # if request.user.is_authenticated:
        #     if request.user.has_perm('front.add_article'):
        #         return render(request, 'add_article.html')
        #     else:
        #         return HttpResponse(content='暂无权限访问该页面', status=403)
        # else:
        #     return redirect(reverse('signin'))
        # print(request.user.is_authenticated)

        # if request.user.has_perm('front.add_article'):
        #     return render(request, 'add_article.html')
        # else:
        #     return HttpResponse(content='暂无权限访问该页面', status=403)

        # 使用 permission_required
        return render(request, 'add_article.html')

    # @method_decorator([login_required(login_url='/signin/')], name='get')
    @method_decorator([permission_required(perm='front.add_article', login_url='/signin/')], name='get')
    def dispatch(self, request, *args, **kwargs):
        return super(AddArticleView, self).dispatch(request, *args, **kwargs)


# TODO 分组
class GroupView(View):
    def get(self, request, *args, **kwargs):
        # 1.创建分组
        # group = Group.objects.create(name='运营')
        # 获取分组
        group = Group.objects.filter(name='运营').first()

        # 2.添加分组权限
        # 2.1 获取Article模型contenttype
        # content_type = ContentType.objects.get_for_model(Article)
        # permissions = Permission.objects.filter(content_type=content_type)
        # for permission in permissions:
        #     print(permission)

        # 3.对group分组添加权限
        # group.permissions.add(*permissions)

        # 4.对用户添加分组
        user = User.objects.first()
        # user.groups.add(group)
        # user.save()

        # 5.获取用户所有分组
        # print(user.groups)

        # 6.获取用户所属分组的权限
        print(user.get_group_permissions())
        # 7.获取用户的所有权限
        print(user.get_all_permissions())

        # 8.判断用户是否拥有某个权限
        # 1. 首先判断user.permissions下有没有这个权限，如果有，就True
        # 2. 如果user.permissions下没有这个权限，那么就会判断
        if user.has_perms(['front.add_article', 'front.black_article']):
            print('拥有上述列举权限')
        else:
            print('没有上述权限')
        return HttpResponse('分组添加成功')
